package leetcode.code2033;

import java.util.Arrays;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution2 implements IDebug {

	public int minOperations(int[][] grid, int x) {
		int m = grid.length, n = grid[0].length;
		int mod = -1;
		int max = Integer.MIN_VALUE;
		int[] nums = new int[m *n];
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				int cur = grid[i][j];
				if (mod == -1) {
					mod = cur % x;
				} else if ((cur % x) != mod) {
					return -1;
				}
				max = Math.max(max, cur);
				nums[i*n+j] = cur;
			}
		}
		Arrays.sort(nums);
		H.print(nums);
		int sum = 0;
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				int cur = grid[i][j] - x;
				sum += (max - cur) / x;
			}
		}
		int size = m * n;
		int div = sum / size;
		mod = sum % size;
		int diff = mod > (size - mod) ? div : div + 1;
		int ans = 0;
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				int cur = grid[i][j];
				int off = (max - cur) / x;
				int ans1 = Math.abs(off - diff);
				ans += ans1;
			}
		}
		return ans;
	}

	@Override
	public void debug4() {
//		[[980,476,644,56],[644,140,812,308],[812,812,896,560],[728,476,56,812]]
//				84
		H.compare(45, this.minOperations(
				H.str2array1("[[980,476,644,56],[644,140,812,308],[812,812,896,560],[728,476,56,812]]"), 84));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
	}

}
